package com.adgox.tiantianbiting.home.programCustomBuy;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.adapter.ProgramCustomBuyAdapter;
import com.adgox.tiantianbiting.bean.PageBean;
import com.adgox.tiantianbiting.bean.ProgramChooseBean;
import com.adgox.tiantianbiting.bean.SubProgramBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.mine.wallet.MyWalletActivity;
import com.adgox.tiantianbiting.widget.MyGridView;
import com.bumptech.glide.Glide;
import com.rae.swift.session.SessionManager;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class ProgramCustomBuyActivity extends AppCompatActivity implements ProgramCustomBuyContract.View, AdapterView.OnItemClickListener, ProgramCustomBuyAdapter.OnItemClickListener, View.OnClickListener {

    @BindView(R.id.tv_choose)
    TextView tvChoose;
    @BindView(R.id.grid_view)
    MyGridView gridView;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.icon_arrow)
    ImageView iconArrow;
    @BindView(R.id.tv_total_season)
    TextView tvTotalSeason;
    @BindView(R.id.tv_select_all)
    TextView tvSelectAll;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    private ProgramCustomBuyContract.Presenter mPresenter;
    private int programId;
    private boolean isGridViewVisiable;
    private boolean isSelectedAll = true;
    private int totalResults;
    private ArrayList<Integer> selectedPositions = new ArrayList<>();
    private ProgramCustomBuyAdapter adapter;
    private List<ProgramChooseBean> mList;
    private ArrayList<Map<String, String>> dataList;
    private Dialog dDialog;
    private SubProgramBean programInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_program_custom_buy);
        ButterKnife.bind(this);

        programId = getIntent().getIntExtra("programId", -1);
        if (programId == -1) {
            Toast.makeText(this, "获取栏目信息出错", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }


        new ProgramCustomBuyPresenterImpl(this);

        //获取第一页最多50项数据展示
        mPresenter.getProgramSeasonList(programId, 1, 50);
    }

    @Override
    public void setPresenter(ProgramCustomBuyContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void onSetProgramInfo(SubProgramBean bean) {
        if (bean == null) return;
        programInfo = bean;
        //设置总集数显示
        tvTotalSeason.setText("共" + bean.getTotalSeason() + "集");
        //设置gridview数据展示
        int totalItem = totalResults % 50 == 0 ? totalResults / 50 : (totalResults / 50 + 1);

        dataList = new ArrayList<>();
        for (int i = 0; i < totalItem; i++) {
            HashMap<String, String> map = new HashMap<>();
            map.put("text", (i * 50 + 1) + "-" + (i == totalItem - 1 ? totalResults : (i + 1) * 50));
            dataList.add(map);
        }
        String[] from = {"text"};
        int[] to = {R.id.tv};
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, dataList, R.layout.item_grid_view, from, to);
        gridView.setAdapter(simpleAdapter);
        gridView.setOnItemClickListener(this);

    }

    @Override
    public void onSetProgramSeasonList(PageBean<ProgramChooseBean> list) {
        mList = list.getData();

        //选集按钮文字更改
        tvChoose.setText("选集(" + mList.get(0).getSeason() + "-" + mList.get(mList.size() - 1).getSeason() + ")");

        selectedPositions.clear();
        //默认全选
        for (int i = 0; i < mList.size(); i++) {
            selectedPositions.add(i);
        }

        totalResults = list.getTotalResults();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);

        adapter = new ProgramCustomBuyAdapter(mList, selectedPositions);
        adapter.onSetItemClickListener(this);
        recyclerView.setAdapter(adapter);

        //获取节目详情，之所以放在这里，是因为gridview展示需要的实际集数只能先通过recyclerview的数据请求获取
        mPresenter.getProgramInfo(programId);

    }

    @Override
    public void onBuySuccess() {
        if (dDialog != null) dDialog.dismiss();
        Toast.makeText(this, "购买成功，请返回刷新", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBuyFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.img_finish)
    public void onVFinishClicked() {
        finish();
    }

    //点击展开或隐藏选集列表
    @OnClick({R.id.tv_choose, R.id.icon_arrow})
    public void onViewClicked(View view) {
        //防止连续点击
        tvChoose.setClickable(false);
        iconArrow.setClickable(false);

        if (isGridViewVisiable) {
            //可见就隐藏
            gridView.setVisibility(View.GONE);
            isGridViewVisiable = false;
            iconArrow.setImageResource(R.drawable.red_arrow_down);
        } else {
            //隐藏就可见
            gridView.setVisibility(View.VISIBLE);
            isGridViewVisiable = true;
            iconArrow.setImageResource(R.drawable.red_arrow_up);
            //rv自动滑到最上面，不然gridview就看不见了
            scrollView.scrollTo(0, 0);
        }

        tvChoose.setClickable(true);
        iconArrow.setClickable(true);
    }


    //gridview条目点击
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        mPresenter.getProgramSeasonList(programId, (i + 1), 50);
        tvChoose.setText(dataList.get(i).get("text"));
        tvChoose.performClick();
    }


    //点击全选，或取消全选
    @OnClick(R.id.tv_select_all)
    public void onAllClicked() {
        tvSelectAll.setClickable(false);
        if (isSelectedAll) {
            //取消全选
            selectedPositions.clear();
            adapter.notifyDataSetChanged();
            isSelectedAll = false;
            tvSelectAll.setText("全选本页");
        } else {
            //全选
            for (int i = 0; i < 50; i++) {
                selectedPositions.add(i);
            }
            adapter.notifyDataSetChanged();
            isSelectedAll = true;
            tvSelectAll.setText("取消全选");
        }
        tvSelectAll.setClickable(true);
    }

    @Override
    public void onItemClick(View view, int position) {
        if (selectedPositions.contains(position)) {
            //这里强转为Integer，因为remove方法如果传进去的是int的话，默认是移除对应index的元素，而不是传进去的元素。
            selectedPositions.remove((Integer) position);
        } else {
            selectedPositions.add(position);
        }

        //判断是否还是全选状态，如果不是，更改全选按钮上文字。判断依据是长度，如果不为mList的长度，则肯定不是全选状态
        if (selectedPositions.size() == mList.size()) {
            tvSelectAll.setText("取消全选");
            isSelectedAll = true;
        } else {
            tvSelectAll.setText("全选本页");
            isSelectedAll = false;
        }

        adapter.setSelectedPositions(selectedPositions);
        adapter.notifyDataSetChanged();

    }

    @OnClick(R.id.tv_buy_chosen)
    public void onBuyChosenClicked() {
        if (selectedPositions.size() == 0) {
            Toast.makeText(this, "未选中任何节目", Toast.LENGTH_SHORT).show();
            return;
        }
        dDialog = new Dialog(this);
        Window window = dDialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setContentView(R.layout.dialog_buy_detail);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        ImageView imgX = dDialog.findViewById(R.id.img_X);
        ImageView imgBook = dDialog.findViewById(R.id.img_book);
        TextView tvBookName = dDialog.findViewById(R.id.tv_book_name);
        TextView tvBuySeasons = dDialog.findViewById(R.id.tv_buy_seasons);
        TextView tvTotalCost = dDialog.findViewById(R.id.tv_total_cost);
        TextView tvToRecharge = dDialog.findViewById(R.id.tv_to_recharge);
        TextView tvBuy = dDialog.findViewById(R.id.tv_buy);

        Glide.with(this).load(programInfo.getShareImageUrl()).into(imgBook);
        tvBookName.setText(programInfo.getTitle());
        tvBuySeasons.setText("集数 " + selectedPositions.size() + "集");
        double cost = 0;
        for (int i = 0; i < selectedPositions.size(); i++) {
            cost += mList.get(selectedPositions.get(i)).getPrice();
        }
        BigDecimal bg = new BigDecimal(cost);
        double nc = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tvTotalCost.setText("价格 " + nc + "听币");
        UserInfo user = SessionManager.getDefault().getUser();
        if (user.getBalance() < cost) {
            tvToRecharge.setVisibility(View.VISIBLE);
        } else {
            tvToRecharge.setVisibility(View.GONE);
        }

        imgX.setOnClickListener(this);
        tvToRecharge.setOnClickListener(this);
        tvBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<Long> longs = new ArrayList<>();
                for (int i = 0; i < selectedPositions.size(); i++) {
                    longs.add((long) mList.get(selectedPositions.get(i)).getId());
                }
                mPresenter.buySelected(programId, longs);
            }
        });
        dDialog.setCanceledOnTouchOutside(false);
        dDialog.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_X:
                dDialog.dismiss();
                break;
            case R.id.tv_to_recharge:
                startActivity(new Intent(this, MyWalletActivity.class));
                dDialog.dismiss();
                break;
        }
    }

    @OnClick(R.id.tv_buy_all)
    public void onBuyAllClicked() {
        Toast.makeText(this, "暂不支持全集购买", Toast.LENGTH_SHORT).show();
    }
}
